package com.modules.config;

import com.common.bean.config.FilterIgnorePropertiesConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsUtils;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.List;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private FilterIgnorePropertiesConfig filterIgnorePropertiesConfig;

    @Override
    public void configure(WebSecurity web) {
        List<String> ignoringList = filterIgnorePropertiesConfig.getUrls();
        String[] igs = new String[ignoringList.size()];
        ignoringList.toArray(igs);
        web.ignoring().antMatchers(igs);
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.requestMatchers().and().csrf().and().cors().disable().authorizeRequests()
                .requestMatchers(CorsUtils::isPreFlightRequest).permitAll();
//                .and()
//                .requestMatchers().antMatchers(HttpMethod.OPTIONS, "/**");
        http.authorizeRequests().anyRequest()
                .access("@permissionService.hasPermission(request,authentication)");
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
